package com.gxgeek.redis.application.redistool;

import com.gxgeek.redis.application.redistool.function.JedisExecutorInterface;
import com.gxgeek.redis.application.redistool.function.JedisExecutorNotReturnInterface;
import com.gxgeek.redis.application.redistool.function.JedisExecutorWithPiplineInterface;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.Pipeline;

import java.io.IOException;
import java.util.List;

/**
 * redis 操作
 *
 * @author gaoxing
 * @create 2017-09-26 下午3:24
 */
public class JedisExecutor {
    private static GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
    // 初始化Jedis连接池
    private static JedisPool jedisPool = new JedisPool(poolConfig, "127.0.0.1", 6379, 1000);
//
//    public JedisExecutor(GenericObjectPoolConfig config ,JedisPool jedisPool){
//        JedisExecutor.poolConfig =config;
//        JedisExecutor.jedisPool =jedisPool;
//    }

    /**
     * 普通操作执行
     *
     * @param executor
     * @param <T>
     * @return
     */
    public static <T extends Object> T execute(JedisExecutorInterface<T> executor) {
        // 返回值
        T Object;

        try (   // 获取连接池里的连接  这里会自动释放资源
                Jedis jedis = jedisPool.getResource();
        ) {
            // 业务操作
            Object = executor.execute(jedis);
        }
        return Object;
    }


    /**
     * 普通操作执行 没有返回值NR not return
     *
     * @param executor
     */
    public static void executeNR(JedisExecutorNotReturnInterface executor) {
        // 返回值
        try (   // 获取连接池里的连接  这里会自动释放资源
                Jedis jedis = jedisPool.getResource();
        ) {
            // 业务操作
            executor.execute(jedis);
        }
    }

    public static List<Object> executeWithPipline(JedisExecutorWithPiplineInterface executor) {

        try (   // 获取连接池里的连接  这里会自动释放资源
                Jedis jedis = jedisPool.getResource();
                Pipeline pipeline = jedis.pipelined();
        ) {
            // 业务操作
            executor.execute(pipeline);
            //
            return pipeline.syncAndReturnAll();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    public static void executeWithPiplineNR(JedisExecutorWithPiplineInterface executor) {

        try (   // 获取连接池里的连接  这里会自动释放资源
                Jedis jedis = jedisPool.getResource();
                Pipeline pipeline = jedis.pipelined();
        ) {
            // 业务操作
            executor.execute(pipeline);
            //
            pipeline.sync();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


}
